package controllers

import (
	"crmObject/models"
	"crmObject/util"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"strconv"
)

type MarketingOpportunitiesController struct {
	beego.Controller
}

//查询有关营销机会的数据

func (c *MarketingOpportunitiesController) Get() {
	newOrm := orm.NewOrm()
	newOrm.QueryTable("")
}

var marketingOpportunities models.MarketingOpportunities
var customers models.Customers
var mo []models.MarketingOpportunities

// 添加营销机会

func (c *MarketingOpportunitiesController) InsertMarketingOpportunities() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	//TODO 判断接收的信息是否为空
	//TODO session名规定为常量
	//获取本次插入营销机会的人id
	conn := util.RedisPool.Get()
	// 从 Redis 中读取 JSON 字符串
	userJSON, err := redis.String(conn.Do("GET", util.USERS))
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	// 将 JSON 字符串反序列化为结构体
	err = json.Unmarshal([]byte(userJSON), &user)

	newOrm := orm.NewOrm()
	//TODO 优化客户和联系人是一对多关系
	//通过客户姓名拿到对应的联系人id,先拿到客户的id,在拿联系人的id
	customers.CustomerName = marketingOpportunities.Customers.CustomerName
	//第一个参数为对象,第二个参数是对应的对象的条件参数
	//客户外键
	err = newOrm.Read(&customers, "CustomerName")
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	//创建信息的工作人员姓名
	marketingOpportunities.CreateUser = user.Username
	//插入时间,不需要插入,通过orm关键字,插入时会自动生成
	//要转换的字符串时间
	//formatTime := time.Now().Format("2006-01-02 15:04:05")
	//时间字符串的格式
	//format := "2006-01-02 15:04:05"
	//parseTime, err := time.Parse(format, formatTime)
	//if err != nil {
	//	c.Data["json"] = LoginResponse{Success: false, Message: "请求解析失败"}
	//	c.ServeJSON()
	//	return
	//}
	//marketingOpportunities.AddTime = parseTime
	//更新时间
	//marketingOpportunities.UpdateTime = parseTime
	//插入customers_id外键
	marketingOpportunities.Customers = &customers
	marketingOpportunities.OpportunityID = 0
	_, err = newOrm.Insert(&marketingOpportunities)
	fmt.Println(err)
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	errCode := 200
	newError := util.NewError(errCode)
	c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
	defer conn.Close()
	c.ServeJSON()
}

//修改营销机会. 需要携带营销机会id

func (c *MarketingOpportunitiesController) UpdateMarketingOpportunities() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 504
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	//TODO 判断值是否为空
	//TODO 判断哪些值是需要修改的
	newOrm := orm.NewOrm()
	//更新时间
	//formatTime := time.Now().Format("2006-01-02 15:04:05")
	//时间字符串的格式
	//format := "2006-01-02 15:04:05"
	//parseTime, err := time.Parse(format, formatTime)
	//mo.UpdateTime = parseTime
	//session中获取是谁修改了,如果不是本人就要修改usersId
	conn := util.RedisPool.Get()
	// 从 Redis 中读取 JSON 字符串
	userJSON, err := redis.String(conn.Do("GET", util.USERS))
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	// 将 JSON 字符串反序列化为结构体
	err = json.Unmarshal([]byte(userJSON), &user)

	marketingOpportunities.CreateUser = user.Username
	//通过客户姓名拿到对应的联系人id,先拿到客户的id,在拿联系人的id
	customers.CustomerName = marketingOpportunities.Customers.CustomerName
	//客户外键
	err = newOrm.Read(&customers, "CustomerName")
	marketingOpportunities.Customers = &customers
	//update方法可以根据结构体中的主键直接作为条件  //修改外键值时----列名是结构体对象名或者对应的参数名
	_, err = newOrm.Update(&marketingOpportunities, "opportunity_name", "opportunity_status", "chance", "marketing_describe", "Customers", "allocation_user")
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	errCode := 200
	newError := util.NewError(errCode)
	c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
	defer conn.Close()
	c.ServeJSON()
}

//删除营销机会(接收营销id和外键客户id)

func (c *MarketingOpportunitiesController) DeleteMarketingOpportunities() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 504
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	newOrm := orm.NewOrm()
	//delete不需要外键会直接删除
	_, err = newOrm.Delete(&marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	errCode := 200
	newError := util.NewError(errCode)
	c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
	c.ServeJSON()
}

//通过客户名或者创建人查询
//TODO 查询过后的也是分页展示,通过一些参数来表示这是分页的查询结果

func (c *MarketingOpportunitiesController) SelectMarketingOpportunities() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 504
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	userName := marketingOpportunities.CreateUser
	customersName := marketingOpportunities.Customers.CustomerName
	newOrm := orm.NewOrm()

	//TODO 虚假数据
	pagination := util.NewPagination(4, 1, util.PAGESIZE)
	if userName == "" && customersName == "" {
		fmt.Println(err)
		errCode := 505
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	} else if userName != "" {
		if customersName != "" {
			//两个都存在
			_, err = newOrm.QueryTable("marketingOpportunities").Filter("create_user__contains", userName).Filter("customer_name__contains", customersName).RelatedSel().All(&mo)
		} else {
			//用户名称有
			_, err = newOrm.QueryTable("marketingOpportunities").Filter("create_user__contains", userName).RelatedSel().All(&mo)
			if err != nil {
				fmt.Println(err)
				errCode := 500
				newError := util.NewError(errCode)
				c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
				c.ServeJSON()
				return
			}
		}
	} else {
		//客户名称有
		_, err = newOrm.QueryTable("marketingOpportunities").Filter("customer_name__contains", customersName).RelatedSel().All(&mo)
	}
	c.Data["page"] = pagination
	c.Data["marketingOpportunities"] = mo
	c.TplName = "omtables.html"
	//这里可以直接返回已经渲染好的页面的代码给ajax的data
}

//分页显示所有信息

func (c *MarketingOpportunitiesController) ListMarketingOpportunities() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	//当前页
	pageNoStr := c.GetString("pageNo")
	if pageNoStr == "" {
		//参数为空,错误处理
		//errCode := 505
		//newError := util.NewError(errCode)
		//c.Data["error"] = newError
		//c.TplName = "error.html"
		pageNoStr = "1"
	}
	pageNo, err := strconv.Atoi(pageNoStr)
	newOrm := orm.NewOrm()
	//总记录数
	totalPageCount, err := newOrm.QueryTable(&marketingOpportunities).Count()
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["error"] = newError
		c.TplName = "error.html"
	}
	pagination := util.NewPagination(int(totalPageCount), pageNo, util.PAGESIZE)

	_, err = newOrm.QueryTable("marketingOpportunities").RelatedSel().Limit(util.PAGESIZE, (pageNo-1)*util.PAGESIZE).All(&mo)
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["error"] = newError
		c.TplName = "error.html"
	}
	c.Data["marketingOpportunities"] = mo
	c.Data["page"] = pagination
	conn := util.RedisPool.Get()
	// 从 Redis 中读取 JSON 字符串
	userJSON, err := redis.String(conn.Do("GET", util.USERS))
	if err != nil {
		fmt.Println(err)
	}
	// 将 JSON 字符串反序列化为结构体
	err = json.Unmarshal([]byte(userJSON), &user)

	c.Data["user"] = user
	defer conn.Close()
	c.TplName = "omtables.html"
}

//查询单条要修改的数据

func (c *MarketingOpportunitiesController) UpdateSelect() {
	// 在进入每个页面之前进行登录状态的判断
	if !IsUserLoggedIn() {
		c.Redirect("/login", 302) // 未登录则重定向到登录页面
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 504
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	newOrm := orm.NewOrm()
	err = newOrm.QueryTable(&marketingOpportunities).Filter("opportunity_i_d", marketingOpportunities.OpportunityID).RelatedSel().One(&marketingOpportunities)
	if err != nil {
		fmt.Println(err)
		errCode := 500
		newError := util.NewError(errCode)
		c.Data["json"] = LoginResponse{Code: newError.Code, Message: newError.Message}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"OpportunityID":     marketingOpportunities.OpportunityID,
		"OpportunityName":   marketingOpportunities.OpportunityName,
		"OpportunityStatus": marketingOpportunities.OpportunityStatus,
		"Chance":            marketingOpportunities.Chance,
		"MarketingDescribe": marketingOpportunities.MarketingDescribe,
		"AllocationUser":    marketingOpportunities.AllocationUser,
		"CustomersName":     marketingOpportunities.Customers.CustomerName,
	}
	c.ServeJSON()
}
